package com.siyu.preplan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyu.common.config.minio.MinIOConfigProperties;
import com.siyu.common.constant.MinioOrOssConstants;
import com.siyu.common.core.domain.AjaxResult;
import com.siyu.common.utils.aliyun.service.FileOssStorageService;
import com.siyu.common.utils.minio.service.FileStorageService;
import com.siyu.common.utils.uuid.IdUtils;
import com.siyu.preplan.dto.PlanListDto;

import com.siyu.preplan.planpdocument.domain.PlanPDocument;
import com.siyu.preplan.planpdocument.mapper.PlanPDocumentMapper;
import com.siyu.preplan.planpdocument.service.IPlanPDocumentService;
import com.siyu.preplan.planpdocument.service.impl.PlanPDocumentServiceImpl;
import com.siyu.preplan.service.PlanPService;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

@Service
public class PlanPServiceImpl implements PlanPService {

    private static Boolean minioOrOss = MinioOrOssConstants.getMinioOrOss();

    @Autowired
    private PlanPDocumentMapper planPDocumentMapper;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IPlanPDocumentService planPDocumentService;

    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    @Autowired
    private FileOssStorageService fileOssStorageService;


    @Override
    public Object getPlanList(PlanListDto planListDto) {
        HashMap<String, ArrayList<PlanPDocument>> resultHasMap = new HashMap<>();
        // 判断是时间分类查询还是区分类查询
        if (planListDto.getQueryType() == 0) {
            // 查询有哪些年份
            ArrayList<String> strings = planPDocumentMapper.getQueryYear(planListDto.getRscd());
            for (int i = 0; i < strings.size(); i++) {
                // 每一个年份查询数据存入map
                String queryType = strings.get(i);
                ArrayList<PlanPDocument> planPDocuments = planPDocumentMapper.getQueryYearPlanPDocument(queryType, planListDto.getPlanName(), planListDto.getRscd());
                resultHasMap.put(queryType, planPDocuments);
            }
        } else if (planListDto.getQueryType() == 1) {
            // 查询有哪些区
            ArrayList<String> strings = planPDocumentMapper.getQueryArea(planListDto.getRscd());
            for (int i = 0; i < strings.size(); i++) {
                // 每一个区查询数据存入map
                String queryType = strings.get(i);
                ArrayList<PlanPDocument> planPDocuments = planPDocumentMapper.getQueryAreaPlanPDocument(queryType, planListDto.getPlanName(), planListDto.getRscd());
                resultHasMap.put(queryType, planPDocuments);
            }
        }

        return resultHasMap;
    }

    @Override
    public ResponseEntity<AjaxResult> uploadPlan(MultipartFile file, String year, String area, String rscd) {
        Objects.requireNonNull(file, "文件不能为空");
        Objects.requireNonNull(year, "年份不能为空");
        Objects.requireNonNull(area, "地区不能为空");

        try (InputStream inputStream = file.getInputStream()) {

            String id = IdUtils.getId();
            String fileName = id + "-" + file.getOriginalFilename();
            String fileUrl = "";
            String path = "";
            if (minioOrOss) {
                path = fileOssStorageService.uploadWordFile("planfile", fileName, inputStream);
            } else {
                fileUrl = fileStorageService.uploadWordFile("planfile", fileName, inputStream);
                URL url = new URL(fileUrl);
                path = url.getPath();
                path = minIOConfigProperties.getReadPath() + path;
            }

            PlanPDocument planPDocument = PlanPDocument.builder()
                    .id(id)
                    .planUrl(path)
                    .planName(fileName.split("-")[1])
                    .year(year)
                    .area(area)
                    .rscd(rscd)
                    .build();

            planPDocumentService.save(planPDocument);
            return ResponseEntity.ok(AjaxResult.success("文件上传成功"));
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(AjaxResult.error("文件上传时发生错误: " + e.getMessage()));
        }
    }

    @Override
    public ResponseEntity<Resource> downloadFile(String id) throws MalformedURLException, FileNotFoundException, UnsupportedEncodingException {
        PlanPDocument planPDocument = planPDocumentService.getById(id);
        String planUrl = planPDocument.getPlanUrl();
        byte[] bytes = null;
        if (minioOrOss) {
            bytes = fileOssStorageService.downLoadFile(planUrl);
        } else {
            URL url = new URL(planUrl);
            String path = url.getPath();
            path = minIOConfigProperties.getEndpoint() + path;
            bytes = fileStorageService.downLoadFile(path);
        }

        // 如果需要，可以从计划文档中提取文件名
        String fileName = "downloadedFile"; // 这里应该替换为实际的文件名
        if (planPDocument != null && planPDocument.getPlanUrl() != null) {
            int lastSlashIndex = planPDocument.getPlanUrl().lastIndexOf('/');
            if (lastSlashIndex > 0) {
                fileName = planPDocument.getPlanUrl().substring(lastSlashIndex + 1);
                fileName = fileName.split("-")[1];
            }
        }

        ByteArrayResource resource = new ByteArrayResource(bytes);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        // 注意：文件名应进行URL编码，以确保在所有浏览器和系统中正确显示
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        headers.setContentLength(bytes.length);

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    /**
     * 删除minio/oss文件
     * @param id
     * @return
     */
    @Override
    public AjaxResult deletefile(String id) {
        try {
            PlanPDocument planPDocument = planPDocumentService.getById(id);
            String planUrl = planPDocument.getPlanUrl();
            if (minioOrOss){
                fileOssStorageService.delete(planUrl);
            }else {
                URL url = new URL(planUrl);
                String path = url.getPath();
                path = minIOConfigProperties.getEndpoint() + path;
                fileStorageService.delete(path);
            }
            planPDocumentService.deletePlanPDocumentById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("删除失败!");
        }

        return AjaxResult.success("删除成功!");
    }
}
